from datetime import datetime, timedelta
from ..repositories import home_repositories

async def get_statistics(user_id):
    """
    获取用户收支统计
    :param user_id: 用户ID
    :return: 包含收入和支出统计的字典
    """
    try:
        # 获取当月所有账单
        now = datetime.now()
        first_day = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        
        result = await home_repositories.get_statistics(
            user_id=user_id,
            start_date=first_day,
            end_date=now
        )
        
        if result is None:
            return {"code": 1, "message": "获取统计信息失败"}
            
        return {
            "code": 0,
            "data": {
                "income": float(result["income"]),
                "expense": float(result["expense"])
            }
        }
    except Exception as e:
        print(f"获取统计信息失败: {str(e)}")
        return {"code": 1, "message": f"获取统计信息失败: {str(e)}"}

async def get_chart_data(user_id):
    """
    获取最近6个月的收支趋势数据
    :param user_id: 用户ID
    :return: 包含月份、收入和支出数据的字典
    """
    try:
        # 获取最近6个月的数据
        now = datetime.now()
        six_months_ago = (now - timedelta(days=180)).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        
        result = await home_repositories.get_chart_data(
            user_id=user_id,
            start_date=six_months_ago,
            end_date=now
        )
        
        if result is None:
            return {"code": 1, "message": "获取图表数据失败"}
            
        return {
            "code": 0,
            "data": result
        }
    except Exception as e:
        print(f"获取图表数据失败: {str(e)}")
        return {"code": 1, "message": f"获取图表数据失败: {str(e)}"}